package gz.copydatabase.Utils;

/**
 * Created by Administrator on 2016/10/9.
 */

import android.os.Environment;
import android.os.StatFs;
import android.util.Base64;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import gz.copydatabase.Application.ApplicationExd;


public class FileUtils {
    public  static String SDPATH= Environment.getExternalStorageDirectory() + "/";
    public String getSDPATH() {
        return SDPATH;
    }
    public FileUtils() {
        //得到当前外部存储设备的目录
        // /SDCARD
        SDPATH = Environment.getExternalStorageDirectory() + "/";
    }
   
    public static File creatSDFile(String fileName) throws IOException {
        File file = new File(SDPATH + fileName);
        file.createNewFile();
        return file;
    }

    
    public static File creatSDDir(String dirName) {
        File dir = new File(SDPATH + dirName);
        dir.mkdirs();
        return dir;
    }

    
    public static boolean isFileExist(String fileName){
        File file = new File(SDPATH + fileName);
        return file.exists();
    }

   
    public static File write2SDFromBytes(String path, String fileName, byte[] bytes){
        File file = null;
        OutputStream output = null;
        if(bytes==null)
             return null;
        try{
            creatSDDir(path);
            file = creatSDFile(path + fileName);
            output = new FileOutputStream(file);
            output.write( bytes);
            output.flush();
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            try{
                output.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
        return file;
    }
    public static String subPath(String path) {
        if (path==null||path.isEmpty()) {
            return "";
        } else {
            return  path.substring(path.length()-27);
        }
    }
    public static String imageToBase64(String path) {
        byte[] data = null;
        String str="";
        try {
            InputStream in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            in.close();
            str= Base64.encodeToString(data, Base64.DEFAULT);
        } catch (Exception e) {
          Log.i("hello",e.toString());
        }finally {
            return  str;
        }
    }
    public boolean removePicture(String picPath){
        File file = new File(SDPATH + picPath);
        if(file.exists()) {
            file.delete();
            return true;
        }
        return false;
    }
    public static String saveString(String str) {
        String splitStr[]=new SimpleDateFormat("HH:mm:ss:SSS yyyy-MM-dd").format(new Date()).split(" ");
        String path="BankBox/Log/";
        String fileName=splitStr[1]+".txt";
        File resultFile;
        try {
                resultFile = write2SDFromString(path,fileName,splitStr[0]+" "+str);
                if (resultFile == null)
                    return null;
        } catch (Exception e) {
            e.printStackTrace();
            return  null;
        }
        return  resultFile.toString();
    }

   public static File write2SDFromString(String path, String fileName, String str){
       File file = null;
       FileWriter fw = null;
       try{
           creatSDDir(path);
           file = creatSDFile(path + fileName);
           fw = new FileWriter(file,true);
           synchronized(FileUtils.class) {
               fw.append(str);
               fw.flush();
               fw.close();
           }
       }
       catch(Exception e){
           e.printStackTrace();
       }
       return  file;
   }
    public static String savePicture(byte[] bytes) {
        Date date= new Date();
        String dateStr=new SimpleDateFormat("yyyy-MM-dd").format(date);
        String fileName=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS").format(date)+".jpg";
        String path="Park/Capture/"+dateStr+"/";
        try {
            if(isFileExist(path+fileName)) {
                return null;
            } else {
                File resultFile = write2SDFromBytes(path,fileName,bytes);
                if (resultFile == null)
                    return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return  null;
        }
        return  SDPATH+path+fileName;
    }
   ////得到要删除的文件夹
    public  static File[] getFileNames(String path, final String regexp)
    {
        // 目录
        File directory = new File(path);
        //File[] filesFiles = directory.listFiles();
        File[] filesFiles = directory.listFiles(new FilenameFilter(){
            @Override
            public boolean accept(File dir, String name) {
                try {
                    Pattern pattern = Pattern.compile(regexp);
                    File file = new File(dir.getPath() + "/"+name);
                    // 文件夹过滤掉
//                    if (!file.isDirectory())
//                        return false;
                    return pattern.matcher(name).matches();
                } catch (Exception e) {
                    return false;
                }
            }
        });
        return filesFiles;
    }
    public File[] getCaptureFileNames(){
        return this.getFileNames(SDPATH+"Park/Capture/","\\d{4}-(0[1-9]|1[1-2])-(0[1-9]|[1-2]\\d|3[0-1])");
    }
    public File[] getLogFileNames(){
       return this.getFileNames(SDPATH+"BankBox/Log/","\\d{4}-(0[1-9]|1[1-2])-(0[1-9]|[1-2]\\d|3[0-1])\\.txt");
    }
    public  static  File[] getDbFileNames(){
        return getFileNames(ApplicationExd.settingInfo.getString(SPUtils.Key.USB_PATH),".+\\.db");
    }
    public static File[] getConfigFileNames(){
        return getFileNames(SDPATH+"BankBox/Config/","config.*");
    }
    ///删除文件夹
    public  static void deleteFile(File file)
    {
        if(!file.exists())
            return ;
        if (file.isFile())
        {
            file.delete();
            return;
        }
        if(file.isDirectory())
        {
            File[] files = file.listFiles();//声明目录下所有的文件 files[];
            for (int i = 0;i < files.length;i ++) {//遍历目录下所有的文件
                FileUtils.deleteFile(files[i]);//把每个文件用这个方法进行迭代
            }
            file.delete();
            return ;
        }
    }
    public  long getSDFreeSize(){
        //取得SD卡文件路径
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //空闲的数据块的数量
        long freeBlocks = sf.getAvailableBlocks();
        //返回SD卡空闲大小
        //return freeBlocks * blockSize;  //单位Byte
        //return (freeBlocks * blockSize)/1024;   //单位KB
        return (freeBlocks * blockSize)/1024 /1024; //单位MB
    }

}